<template>
  <view class="player-container">
    <UniMusicHead></UniMusicHead>
    <!-- 唱盘容器 -->
    <view class="disc-container">
      <!-- 指针 -->
      <image 
        class="needle" 
        src="/static/needle.png" 
        :style="needleStyle"
      ></image>
      <!-- 唱盘 -->
      <view class="disc" :style="rotationStyle">
        <image class="disc-bg" src="/static/disc.png"></image>
        <image class="album-art" :src="albumArtUrl" mode="aspectFit"></image>
      </view>
      <!-- 播放按钮 -->
      <view class="center-play-button" @tap="handlePlayPause">
        <text class="iconfont" :class="isPlaying ? 'icon-zanting' : 'icon-bofang'"></text>
      </view>
    </view>
    <!-- 歌词区域 -->
    <view class="lyrics-container">
      <view v-if="lyricsLoading" class="loading-lyrics">
        <text class="loading-text">歌词加载中...</text>
        <view class="loading-spinner"></view>
      </view>
      <view v-else-if="!parsedLyrics.length" class="no-lyrics">
        <text>暂无歌词</text>
      </view>
      <view v-else class="lyric-wrapper">
        <!-- 动态显示三行歌词 -->
        <view 
          v-for="(line, index) in visibleLyrics"
          :key="index"
          class="lyric-line"
          :class="{
            'current': index === 1,
            'previous': index === 0,
            'next': index === 2
          }"
        >
          {{ line.lyric }}
        </view>
      </view>
    </view>
	<!-- 歌曲信息 -->
	<view class="song-info">
	  <text class="song-title">{{ title }}</text><br>
	  <text class="song-artist">{{ artist }}</text>
	  <text class="play-status" v-if="errorMessage">{{ errorMessage }}</text>
	</view>
    <!-- 进度条 -->
    <view class="progress-container">
      <text class="time">{{ formattedCurrentTime }}</text>
      <view class="progress-bar" @tap="handleProgressClick">
        <view class="progress" :style="{ width: progressWidth }"></view>
      </view>
      <text class="time">{{ formattedDuration }}</text>
    </view>
  </view>
</template>

<script>
import { getSongDetail, getSongUrl, getLyric } from '../../common/api.js';

export default {
  data() {
    return {
      title: '',
      artist: '',
      song: { url: '' },
      innerAudioContext: null,
      isPlaying: false,
      albumArtUrl: '',
      rotationDegree: 0,
      currentTime: 0,
      duration: 0,
      isLoading: false,
      errorMessage: '',
      lyrics: '',
      parsedLyrics: [],
      currentLyricIndex: 0,
      lineHeight: 25.6, 
      lyricsLoading: false,
      lyricsError: null,
      needleRotation: -25,
    };
  },
  computed: {
    visibleLyrics() {
      const lines = [];
      // 获取当前歌词的前后各一句
      const prevIndex = Math.max(this.currentLyricIndex - 1, 0);
      const nextIndex = Math.min(this.currentLyricIndex + 1, this.parsedLyrics.length - 1);

      // 构建显示的三行歌词数组
      lines.push(this.parsedLyrics[prevIndex]);
      lines.push(this.parsedLyrics[this.currentLyricIndex]);
      lines.push(this.parsedLyrics[nextIndex]);

      return lines;
    },
    // 新增指针样式计算
    needleStyle() {
      return {
        transform: `rotate(${this.needleRotation}deg)`,
        transformOrigin: '24px 24px', // 根据实际图片调整旋转中心
        transition: 'transform 0.6s cubic-bezier(0.4, 0, 0.2, 1)'
      };
    },
    // 修改rotationStyle应用到唱盘
    rotationStyle() {
      return {
        transform: `rotate(${this.rotationDegree}deg)`,
        transition: this.isPlaying ? 'none' : 'transform 0.3s ease-out'
      };
    },
    progressWidth() {
      return this.duration ? `${(this.currentTime / this.duration) * 100}%` : '0%';
    },
    formattedCurrentTime() {
      return this.formatTime(this.currentTime);
    },
    formattedDuration() {
      return this.formatTime(this.duration);
    }
  },
  methods: {
    // 进度条点击处理
    handleProgressClick(e) {
      if (!this.duration || !this.innerAudioContext) return;
      uni.createSelectorQuery()
        .select('.progress-bar')
        .boundingClientRect(rect => {
          const clickX = e.detail.x - rect.left;
          this.innerAudioContext.seek((clickX / rect.width) * this.duration);
        })
        .exec();
    },

    // 时间格式化
    formatTime(seconds) {
      if (isNaN(seconds)) return '00:00';
      const pad = n => n.toString().padStart(2, '0');
      return `${pad(Math.floor(seconds/60))}:${pad(Math.floor(seconds%60))}`;
    },

    // 旋转动画控制
    startRotation() {
      const animate = () => {
        this.rotationDegree = (this.rotationDegree + 1) % 360;
        this.isPlaying && requestAnimationFrame(animate);
      };
      animate();
    },

    // 播放控制
    async handlePlayPause() {
      if (this.isLoading) return;
      
      try {
        if (!this.innerAudioContext) await this.initializeAudio();
        
        if (this.isPlaying) {
          this.innerAudioContext.pause();
          this.needleRotation = -25; // 复位指针
        } else {
          await this.checkNetwork();
          this.innerAudioContext.play();
          this.needleRotation = 0; // 指针到位
        }
      } catch (error) {
        this.handleError(error.message);
      }
    },
    // 初始化音频
    async initializeAudio() {
      this.innerAudioContext = uni.createInnerAudioContext();
      this.innerAudioContext.src = this.song.url;
      
      this.innerAudioContext.onCanplay(() => this.isLoading = false);
      this.innerAudioContext.onPlay(() => {
        this.isPlaying = true;
        this.startRotation();
      });
      this.innerAudioContext.onPause(() => this.isPlaying = false);
      this.innerAudioContext.onTimeUpdate(() => {
        this.currentTime = this.innerAudioContext.currentTime;
        this.duration = this.innerAudioContext.duration;
        this.updateLyrics(this.currentTime);
      });
      this.innerAudioContext.onError(() => this.handleError('播放失败'));
    },

    // 网络检查
    async checkNetwork() {
      const { networkType } = await uni.getNetworkType();
      if (networkType === 'none') throw new Error('无网络连接');
    },

    // 歌词处理
    async loadLyrics(songId) {
      try {
        this.lyricsLoading = true;
        this.lyricsError = null;
        
        const res = await getLyric(songId);
        if (res?.lrc?.lyric) {
          this.lyrics = res.lrc.lyric;
          this.parseLyrics();
        } else {
          this.lyricsError = '暂无歌词';
        }
      } catch (error) {
        console.error('歌词加载失败:', error);
        this.lyricsError = '歌词加载失败';
      } finally {
        this.lyricsLoading = false;
      }
    },

    scrollToCurrentLyric() {
      if (!this.parsedLyrics.length) return;
      
      // 精确计算参数
      const lineHeight = 25.6; // 必须与CSS line-height值匹配
      
      // 目标位置 = (当前行索引 * 行高) - 容器高度/2 + 行高/2
      const targetScrollTop = this.currentLyricIndex * lineHeight 
        - (180 / 2) 
        + (lineHeight / 2);

      this.scrollTop = Math.max(0, targetScrollTop);
      this.$nextTick(() => {
        this.scrollTop += 0.001;
      });
    },
    parseLyrics() {
      try {
        this.parsedLyrics = this.lyrics.split('\n')
          .map(line => {
            // 增强正则表达式，支持更多时间格式
            const matches = line.match(/\[(\d+):(\d+)([:.])(\d{2,3})\]/);
            if (!matches) return null;
            const minutes = parseInt(matches[1]);
            const seconds = parseInt(matches[2]);
            const separator = matches[3];
            let milliseconds = parseInt(matches[4]);
            // 精确处理毫秒（根据分隔符判断单位）
            if (separator === ':') {  // 格式为[mm:ss:xx] (单位：1/100秒)
              milliseconds *= 10;     // 转换为毫秒
            } else {                  // 格式为[mm:ss.xxx]
              milliseconds = parseInt(matches[4].padEnd(3, '0'));
            }
            // 时间范围校验
            const totalTime = minutes * 60 + seconds + milliseconds / 1000;
            if (isNaN(totalTime) || totalTime < 0) return null;
            return {
              time: totalTime,
              lyric: line.replace(/\[\d+:\d+[:.]\d+\]/g, '').trim() // 移除所有时间标签
            };
          })
          .filter(line => line?.lyric && line.lyric.length > 0)  // 严格过滤空内容
          .sort((a, b) => a.time - b.time);  // 按时间排序
      } catch (e) {
        this.lyricsError = '歌词解析失败';
        this.parsedLyrics = [];
      }
    },
    updateLyrics(currentTime) {
      if (!this.parsedLyrics.length) return;
    
      let low = 0;
      let high = this.parsedLyrics.length - 1;
      let mid;
    
      // 查找最后一个小于等于当前时间的歌词行
      while (low <= high) {
        mid = Math.floor((low + high) / 2);
        if (this.parsedLyrics[mid].time <= currentTime) {
          low = mid + 1;
        } else {
          high = mid - 1;
        }
      }
    
      const newIndex = Math.max(0, high); // 关键修改：使用high代替low-1
      if (this.currentLyricIndex !== newIndex) {
        this.currentLyricIndex = newIndex;
        this.scrollToCurrentLyric();
      }
    },

    // 错误处理
    handleError(message) {
      this.errorMessage = message;
      this.isPlaying = false;
      this.stopRotation();
      uni.showToast({ title: message, icon: 'none' });
    },

    stopRotation() {
      this.rotationDegree = 0;
    }
  },
  onLoad(options) {
    if (!options?.id) {
      this.handleError('无效的歌曲ID');
      return;
    }

    const songId = options.id;
    this.loadLyrics(songId);

    Promise.all([getSongDetail(songId), getSongUrl(songId)])
      .then(([detailRes, urlRes]) => {
        // 处理歌曲信息
        const song = detailRes?.[1]?.data?.songs?.[0];
        if (song) {
          this.title = song.name;
          this.artist = song.ar?.[0]?.name || '未知歌手';
          this.albumArtUrl = song.al?.picUrl;
        }

        // 处理音频URL
        const url = urlRes?.[1]?.data?.data?.[0]?.url;
        if (url) {
          this.song.url = url;
          this.initializeAudio();
        }
      })
      .catch(err => this.handleError('数据加载失败'));
  },
  onUnload() {
    this.innerAudioContext?.destroy();
    this.stopRotation();
  }
};
</script>

<style scoped>
.player-container {
  background: #1a1a1a;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
}

.disc-container {
  position: relative;
  width: 350px;
  height: 350px;
  margin: 40px 0 20px;
}

.needle {
  position: absolute;
  top: -30px;
  left: 50%;
  width: 60px;
  height: 90px;
  z-index: 2;
  transform: rotate(-25deg);
}

.disc {
  position: relative;
  width: 100%;
  height: 100%;
}

.disc-bg {
  position: absolute;
  width: 100%;
  height: 100%;
}

.album-art {
  position: absolute;
  width: 70%;
  height: 70%;
  border-radius: 50%;
  top: 15%;
  left: 15%;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}

.center-play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 3;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(4px);
  transition: all 0.3s ease;
}

.center-play-button .iconfont {
  color: rgba(255, 255, 255, 0.9);
  font-size: 36px;
  margin-left: 4px; /* 视觉居中微调 */
}

.song-info {
  text-align: left;
  margin: 15px 0;
}

.song-title {
  font-size: 20px;
  color: #fff;
  font-weight: 600;
  margin-bottom: 5px;
}

.song-artist {
  font-size: 14px;
  color: rgba(255,255,255,0.7);
}

.progress-container {
  width: 90%;
  margin: 20px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-bar {
  flex: 1;
  height: 3px;
  background: rgba(255,255,255,0.2);
  border-radius: 2px;
}

.progress {
  height: 100%;
  background: #00ffaa;
  border-radius: 2px;
  transition: width 0.1s linear;
}

.time {
  color: rgba(255,255,255,0.7);
  font-size: 12px;
  min-width: 40px;
  font-family: monospace;
}

.lyrics-container {
  height: 180px;
  width: 85%;
  margin: 20px auto;
  padding: 15px 0;
  border-radius: 16px;
  backdrop-filter: blur(20px);
}

.lyric-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: relative;
}

.lyric-line {
  color: rgba(255,255,255,0.4);
  font-size: 16px;
  text-align: center;
  padding: 2px 0;
  transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1);
  transform: translateY(0);
  opacity: 0.6;
}

.lyric-line.current {
  opacity: 1;
  color: #fff;
  font-size: 20px;
  transform: translateY(0) scale(1.1);
}

.lyric-line.previous {
  transform: translateY(-15px) scale(0.9);
  opacity: 0.4;
}

.lyric-line.next {
  transform: translateY(15px) scale(0.9);
  opacity: 0.4;
}

/* 加载状态样式 */
.loading-lyrics {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.loading-text {
  color: rgba(255,255,255,0.6);
  font-size: 14px;
  margin-bottom: 10px;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(255,255,255,0.2);
  border-top-color: #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 无歌词提示样式 */
.no-lyrics {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: rgba(255,255,255,0.4);
  font-size: 14px;
}

.play-status {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 8px;
}
</style>